<template>
  <div id="container" class="container"></div>
</template>
<script setup lang="ts">
import { onMounted, watch } from "vue";
import MapLoader from "@/utils/AMap";
declare const AMap: any;
// 地图
let map: any, marker: any;
const props = defineProps({
  address: {
    type: String,
    default: ""
  },
  lat: {
    type: Number,
    default: 37.870451
  },
  lng: {
    type: Number,
    default: 112.549656
  },
  // 地图key
  apiKey: {
    type: String,
    default: ""
  },
  // 高德地图安全密钥
  securityJsCode: {
    type: String,
    default: ""
  }
});
const emits = defineEmits(["getAddress", "getLatLng"]);

// 点坐标
watch(
  () => props.address,
  (newVal) => {
    console.log(newVal);
    if (newVal && newVal.trim().length > 0) {
      getLatLng(newVal);
    } else {
      console.log("地址为空或无效，跳过 getLatLng 调用");
    }
  }
);
// 密钥
window._AMapSecurityConfig = {
  securityJsCode: props.securityJsCode
};
// 初始化地图
const initAMap = async () => {
  const center = new AMap.LngLat(props.lng, props.lat);
  const myOptions = {
    zoom: 10,
    center: center,
    resizeEnable: true
  };
  map = new AMap.Map("container", myOptions);
  createMarker(center);
  getLatLng();
  getAddress();
};

// 创建点标记
function createMarker(center: any) {
  marker = new AMap.Marker({ position: center });
  map.clearMap();
  marker.setMap(map);
  map.setFitView([marker]);
}

// 根据地址获取经纬度
function getLatLng(address?: string) {
  console.log(address);
  if (address && address.length > 0) {
    try {
      let geocoder = new AMap.Geocoder({
        radius: 1000, // 范围：默认500
        zoomToAccuracy: true
      });
      console.log(geocoder.getLocation);
      geocoder.getLocation(address, (status: string, result: any) => {
        console.log(address);
        console.log(status, result);
        if (status === "complete" && result.info === "OK") {
          var lnglat = result.geocodes[0].location;
          console.log(lnglat);
          emits("getLatLng", [lnglat.lat, lnglat.lng]);
          const center = new AMap.LngLat(lnglat.lng, lnglat.lat);
          createMarker(center);
        } else {
          console.log("查询地址失败");
        }
      });
    } catch (error) {
      console.error("geocoder.getLocation 调用失败", error);
    }
  } else {
    console.log("地址为空或无效，跳过 geocoder.getLocation 调用");
  }
}

// 点击地图获取经纬度已显示地址
function getAddress() {
  map.on("click", function (e: any) {
    marker = new AMap.Marker({
      position: new AMap.LngLat(e.lnglat.lng, e.lnglat.lat)
    });
    map.clearMap();
    marker.setMap(map);
    /** 向父组件传递经纬坐标*******/
    emits("getLatLng", [e.lnglat.lat, e.lnglat.lng]);
    if (e.lnglat.lat !== undefined || e.lnglat.lat !== 0 || e.lnglat.lat !== "") {
      var geocoder = new AMap.Geocoder({
        radius: 1000 // 范围：默认500
      });
      console.log(geocoder);
      geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], (status: string, result: any) => {
        console.log(status, result);
        if (status === "complete" && result.info === "OK") {
          var address = result.regeocode.formattedAddress;
          emits("getAddress", address);
          marker = new AMap.Marker({
            position: new AMap.LngLat(e.lnglat.lng, e.lnglat.lat)
          });
          map.clearMap();
          marker.setMap(map);
        }
      });
    }
  });
}

onMounted(async () => {
  await MapLoader(props.apiKey);
  initAMap();
});
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: 300px;
}
</style>
